/**
 * create by young (young2f@outlook.com) on 2020/10/18
 * 选择目录树下的数据
 * nodes: result,
 table: 'material',
 dispatch: this.props.dispatch,
 tenantCode: _constants.TENANT_CODE,
 parentTable: 'storage',
 dataColumns,
 */


'use strict';

import React from 'react';
import {Button, Form, Layout, Table} from 'antd';
import moment from 'moment';
import 'moment/locale/zh-cn';
import {FormLayout, ModalFooter} from 'antd-extra';
import ViewTitle from '../../ViewTitle';
import notify from '../../NotificationExtra';
import TreeBase from '../../Base/TreeBase';
import DirTree from '../index';

const _ = require('lodash');

moment.locale('zh-cn');

@Form.create()

export default class ModalSelectTreeData extends TreeBase {
  constructor(props) {
    super(props);
    this.state = {
      checkedKeys: [],
      nodes: [],
      dataColumns: [],
      selectedRowKeys: [],
    };
  }

  componentDidMount() {
    this.state.treeNode && this.onLoadData().then(res => {
      this.setState(res);
    });
  }

  async onLoadData() {
    const { dispatch } = this.props;
    const tables = this.props.table && Array.isArray(this.props.table) ? this.props.table : [this.props.table];
    const json = {};
    for (let table of tables) {
      const res = this.props.dispatch({
        type: 'dynamicLabel/getLabels',
        payload: { table },
      });
      const key = `${table}Labels`;
      const temp = res && res.status === 'ok' ? res.result : [];
      json[key] = temp;
    }
    const { treeNode } = this.state;
    const { treeId, table } = treeNode;
    const model = this.getModelStr(table);
    const type = `${table}/find${model}s`;
    const res = await dispatch({
      type,
      payload: { treeId },
    });
    const data = res && res.status === 'ok' ? res.result : [];
    json.data = data;
    return json;
  }

  close = () => {
    const { result, title } = this.props;
    const { data, selectedRowKeys } = this.state;
    if (!selectedRowKeys || !selectedRowKeys.length) {
      notify({ message: `未选择${title}`, type: 'error' });
      return;
    }

    this.props.form.validateFields((err, values) => {
      if (err) {
        notify({ message: '数据未填写', type: 'error' });
        return;
      }
      const selectedDataList = data.filter(item => {
        return _.includes(selectedRowKeys, item._id);
      });

      result(selectedDataList, values);
      this.props.modalRef.close();
    });
  };


  columns = (table, isMaterial) => {
    /**
     * todo 不同的选择对象，动态标签会不同
     * @type {string}
     */
    let title = isMaterial ? '物料' : '产品';
    return this.getColumns(this.state.dataColumns, title);
  };

  create = () => {
    const { createUrl } = this.props;
    window.open(createUrl);
  };

  selectRow = (_id) => {
    const { multiSelect } = this.props;
    let selectedRowKeys = [...this.state.selectedRowKeys];

    if (!multiSelect) {
      selectedRowKeys = [_id];
    } else if (selectedRowKeys.indexOf(_id) >= 0) {
      _.remove(selectedRowKeys, item => item === _id);
    } else {
      selectedRowKeys.push(_id);
    }
    this.setState({ selectedRowKeys });
  };

  content = () => {
    const { data, treeNode, selectedRowKeys } = this.state;
    const { disabledList } = this.props;
    data && data.length && data.map(item => {
      if (_.includes(disabledList, item.code)) {
        item._disabled = true;
      }
    });
    const { createUrl, dataFields, multiSelect, form, onSelected } = this.props;
    const view = selectedRowKeys && selectedRowKeys.length && dataFields ? <FormLayout form={form} cols={2}>
      {dataFields}
    </FormLayout> : null;

    const rowSelection = {
      onChange: (selectedRowKeys) => {
        let _selected = [];
        if (!multiSelect) {
          _selected = [selectedRowKeys[selectedRowKeys.length - 1]];
        } else {
          _selected = selectedRowKeys;
        }

        this.setState({
          selectedRowKeys: _selected,
        });
      },
      selectedRowKeys: selectedRowKeys,
      getCheckboxProps: record => ({
        disabled: record._disabled,
      }),
    };
    if (!treeNode) return;
    let subTitle = this.getTreeSubTitle(treeNode);
    const { table } = treeNode;
    let btnEnable = table === 'product' ? false : true;
    return (<div>
      {<ViewTitle
        style={{ background: '#fff' }}
        title={'待选项'}
        subTitle={subTitle}
        actions={[
          createUrl && <Button onClick={this.create.bind(this)}>新增</Button>,
          <Button onClick={this.componentDidMount.bind(this)}>刷新</Button>,
        ]}
      >
      </ViewTitle>}
      <Table
        columns={this.columns(table, btnEnable)}
        dataSource={data}
        rowKey={record => record._id}
        rowSelection={{
          ...rowSelection,
          onSelect: onSelected,
        }}

        onRow={(record) => ({
          onClick: () => {
            if (!record._disabled) {
              this.selectRow(record._id);
            }
          },
        })
        }
      >
      </Table>
      {view}
    </div>);
  };
  onTreeNodeSelected = (treeNode) => {
    if (!treeNode) {
      return;
    }
    this.state.treeNode = treeNode;
    this.componentDidMount();
    // const { table } = this.props;
    //
    // this.state.treeNode = treeNode;
    // this.requestTreeData(table, treeNode.treeId)
    //   .then(res => {
    //     const { result } = res;
    //     this.setState({ data: result });
    //   });
  };

  render() {
    const { footDisabled, style, table, dispatch, title } = this.props;

    return (
      <Form style={{ ...style }}>
        <Layout>
          <DirTree
            table={table}
            dispatch={dispatch}
            onTreeDelete={this.onTreeDelete}
            onTreeNodeSelected={this.onTreeNodeSelected}
            defaultExpandAll={true}
            disableEdit={true}
            title={title}
          >{this.content()}</DirTree>
          {!footDisabled && <ModalFooter>
            <Button type="primary"
                    onClick={() => {
                      this.close();
                    }}
            >确认
            </Button>
            <Button onClick={() => {
              const { result } = this.props;
              result(undefined);
              this.props.modalRef.close();
            }}
            >取消
            </Button>
          </ModalFooter>}
        </Layout>

      </Form>
    );
  }
}


